package com.hnl.action.attachment;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hnl.core.AttachmentConfig;
import com.hnl.core.aware.HNLAuthAware;
import com.hnl.core.aware.HNLTalentAware;
import com.hnl.dao.AttachmentDAO;
import com.hnl.dao.DAOException;
import com.hnl.dao.HNLDAOFactory;
import com.hnl.dao.MiscDAO;
import com.hnl.to.Attachment;
import com.hnl.to.Misc;
import com.hnl.to.User;
import com.hnl.to.wrapper.AttachmentWrapper;
import com.hnl.util.JSONResponseUtil;

@SuppressWarnings("serial")
public class FileUploadServlet extends HttpServlet implements HNLAuthAware,
		HNLTalentAware {
	public static final Logger LOG = LoggerFactory
			.getLogger(FileUploadServlet.class);

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter writer = resp.getWriter();
		writer.write("call POST with multipart form data");
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (!ServletFileUpload.isMultipartContent(req)) {
			throw new IllegalArgumentException(
					"Request is not multipart, please 'multipart/form-data' enctype for your form.");
		}
		ServletFileUpload uploadHandler = new ServletFileUpload(
				new DiskFileItemFactory());
		PrintWriter writer = resp.getWriter();
		resp.setContentType("text/plain");
		try {
			String talentID = null;
			String systemPath = null;
			String typeName = null;
			String contentType = null;
			Date now = new Date();

			@SuppressWarnings("unchecked")
			List<FileItem> items = uploadHandler.parseRequest(req);

			for (FileItem item : items) {
				if (item.isFormField()) {
					if (item.getFieldName().equals(ATTRIBUTE_TALENT_ID)) {
						talentID = item.getString();
					}
				}
			}

			for (FileItem item : items) {
				if (!item.isFormField()) {
					File dir = new File(AttachmentConfig.tomcatPath
							+ AttachmentConfig.contextPath + "\\" + talentID
							+ "\\" + now.getTime());
					if (!dir.exists()) {
						dir.mkdirs();
					}

					File file = new File(dir, item.getName());
					item.write(file);
					systemPath = file.getPath();
					contentType = item.getContentType();
					typeName = item.getFieldName();
					break; // assume we only get one file at a time
				}
			}

			MiscDAO miscDAO = HNLDAOFactory.getDAOFactory(
					HNLDAOFactory.HNLDAOFACTORY).getMiscDAO();
			Collection<Misc> attachmentMisc = miscDAO
					.loadMiscByMiscTypeName("ATTACHMENT_TYPE");

			Integer typeID = null;
			for (Misc misc : attachmentMisc) {
				if (misc.getMiscName().equals(typeName)) {
					typeID = misc.getMiscID();
				}
			}

			HttpSession session = ((HttpServletRequest) req).getSession();
			User user = (User) session.getAttribute(ATTRIBUTE_USER);

			AttachmentDAO attachmentDAO = HNLDAOFactory.getDAOFactory(
					HNLDAOFactory.HNLDAOFACTORY).getAttachmentDAO();
			Attachment attachment = new Attachment();
			attachment.setAttachmentType(typeID);
			attachment.setContentType(contentType);
			attachment.setSystemPath(systemPath);
			attachment.setTalentId(Integer.valueOf(talentID));
			attachment.setCreateUser(user.getUserID());
			attachment.setCreateDate(now);
			attachment.setModifyDate(now);
			attachment.setModifyUser(user.getUserID());
			attachment.setIsDelete(false);
			attachmentDAO.saveAttachment(attachment);

			AttachmentWrapper attachmentWrapper = new AttachmentWrapper(
					attachment);
			writer.write(JSONResponseUtil
					.getJSONObjectString(attachmentWrapper));
		} catch (FileUploadException e) {
			LOG.error("Error uploading file.", e);
		} catch (DAOException e) {
			LOG.error("Error getting attachment DAO.", e);
		} catch (Exception e) {
			LOG.error("Error writing file to disk.", e);
		} finally {
			writer.close();
		}
	}
}
